<template>
	<view class="login-container">
		<!-- 顶部logo -->
		<view class="logo-area">
			<image class="logo" src="/static/logo.png" mode="aspectFit"></image>
		</view>

		<!-- 登录表单 -->
		<view class="form-area">
			<view class="title">欢迎登录</view>

			<!-- 账号密码登录表单 -->
			<view class="account-login" v-if="loginType === 'account'">
				<view class="input-group">
					<view class="input-item">
						<image class="input-icon" src="/static/account.png"></image>
						<input v-model="accountForm.account" class="input" placeholder="请输入用户名/手机号"
							placeholder-class="input-placeholder" type="text" />
					</view>
					<view class="input-item">
						<image class="input-icon" src="/static/password.png"></image>
						<input v-model="accountForm.password" class="input" placeholder="请输入密码"
							placeholder-class="input-placeholder" password />
					</view>
				</view>

				<view class="flex-between">
					<view class="remember-me">
						<checkbox-group @change="handleRememberChange">
							<checkbox value="remember" :checked="rememberMe" />记住我
						</checkbox-group>
					</view>
					<view class="forgot-password" @click="handleForgotPassword">忘记密码?</view>
				</view>

				<button class="login-btn" @click="handleAccountLogin" :loading="accountLoading">
					登录
				</button>

				<view class="switch-login-type">
					<text @click="switchLoginType('third')">使用第三方登录</text>
				</view>
			</view>

			<!-- 第三方登录方式 -->
			<view class="third-login" v-else>
				<button class="wx-login-btn" @click="handleThirdLogin('wechat')" :loading="wxAuthLoading">
					<text>微信登录</text>
				</button>

				<view class="switch-login-type">
					<text @click="switchLoginType('account')">使用账号密码登录</text>
				</view>
			</view>

			<!-- 协议提示 -->
			<view class="agreement">
				登录即表示您已同意
				<text class="link" @click="navigateToAgreement('user')">《用户协议》</text>
				和
				<text class="link" @click="navigateToAgreement('privacy')">《隐私政策》</text>
			</view>
		</view>
	</view>
</template>

<script>
import { mapGetters, mapActions } from "vuex";
import user from "@/api/user.js";
import api from '@/api/index.js'
export default {
	data() {
		return {
			accountLoading: false, // 账号登录加载状态
			loginType: "account", // 登录方式 account/third
			rememberMe: false, // 是否记住账号
			accountForm: {
				account: "",
				password: "",
			},
			wxAuthLoading: false, // 微信授权加载状态
			jssdkData:''
		};
	},
	computed: mapGetters(["isLogin", "uid", "userInfo"]),
	onLoad() {
		// 检查是否已登录
		if (uni.getStorageSync('token')) {
			this.redirectToHome();
		}

		// 从本地存储获取记住的账号
		this.getRememberAccount();
	},
	methods: {
		...mapActions(["login", "setUserInfo"]),
		// getQueryString方法
		getQueryString(name) {
			if (typeof window === "undefined") return null;
			const reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
			const r = window.location.search.substr(1).match(reg);
			if (r != null) {
				return decodeURIComponent(r[2]);
			}
			return null;
		},

		// 跳转到首页
		redirectToHome() {
			uni.switchTab({
				url: "/pages/index/index",
			});
		},

		// 从本地存储获取记住的账号
		getRememberAccount() {
			const rememberAccount = uni.getStorageSync("rememberAccount");
			if (rememberAccount) {
				this.accountForm.account = rememberAccount.account || "";
				this.accountForm.password = rememberAccount.password || "";
				this.rememberMe = true;
			}
		},

		// 跳转协议页面
		navigateToAgreement(type) {
			uni.navigateTo({
				url: `/pages/agreement/agreement?type=${type}`,
			});
		},

		// 切换登录方式
		switchLoginType(type) {
			this.loginType = type;
		},

		// 记住我状态变化
		handleRememberChange(e) {
			this.rememberMe = e.detail.value.includes("remember");
		},

		// 处理忘记密码
		handleForgotPassword() {
			uni.navigateTo({
				url: "/pages/forgot/forgot",
			});
		},

		// 处理账号密码登录
		async handleAccountLogin() {
			const { account, password } = this.accountForm;

			if (!account) {
				uni.showToast({
					title: "请输入用户名/手机号",
					icon: "none",
				});
				return;
			}

			if (!password) {
				uni.showToast({
					title: "请输入密码",
					icon: "none",
				});
				return;
			}

			this.accountLoading = true;
			try {
				uni.showLoading({
					title: "登录中...",
					mask: true,
				});
				const res = await user.userLogin(this.accountForm);

				if (res.response.statusCode === 200) {
					// 登录成功，保存 token 和用户信息
					// const { token } = res.data.data.userinfo.token;
					// const {  userInfo } = res.data.data.userinfo;
					uni.setStorage({ key: 'token', data: res.data.data.userinfo.token });
					uni.setStorage({ key: 'userInfo', data: res.data.data.userinfo });
					this.redirectToHome();
					// 统一处理登录成功
					// await this.handleLoginSuccess(token, userInfo, {
					// 	account: this.accountForm.account,
					// 	password: this.rememberMe ? this.accountForm.password : "",
					// });
				} else {
					// 统一错误处理
					this.handleLoginError(res);
				}
			} catch (error) {
				this.handleLoginError(error);
			} finally {
				this.accountLoading = false;
				uni.hideLoading();
			}
		},
		// 新增统一处理方法
		handleLoginSuccess(token, userInfo, rememberData = null) {
			// 调用 Vuex 的 LOGIN mutation 保存 token
			this.$store.commit('LOGIN', {
				token: token,
				uid: userInfo // 假设 userInfo 中有 uid 字段
			});

			// 保存用户信息
			this.$store.commit('UPDATE_USERINFO', userInfo);

			if (rememberData && this.rememberMe) {
				uni.setStorage({ key: 'rememberAccount', data: rememberData });
			} else {
				uni.removeStorage({ key: 'rememberAccount' });
			}

			uni.showToast({ title: '登录成功', icon: 'success' });
			setTimeout(() => this.redirectToHome(), 1500);
		},

		handleLoginError(error) {
			const message = error?.data?.msg || error?.message || '登录失败';
			uni.showToast({ title: message, icon: 'none' });
		},
		// 处理第三方登录
		async handleThirdLogin(source) {
			if (source === "wechat") {
				this.wxAuthLoading = true;

				// H5环境微信网页授权登录
				// #ifdef H5
				this.wxH5AuthLogin();
				// #endif

				// 小程序环境下使用小程序登录方式
				// #ifdef MP-WEIXIN
				this.wxMiniProgramLogin();
				// #endif
			}
			// 其他第三方登录方式...
		},
		//获取appid和密钥
		getjssdk(){
			api.getjssdk().then(res => {
				if(res.response.statusCode==200){
					console.log(res.data.data,'this.jssdkData');
					this.jssdkData=res.data
				}
			}).catch(err => {
				console.error(err)
			})
		},
		// H5环境微信网页授权登录
		wxH5AuthLogin() {
			// 微信H5网页授权地址
			console.log(this.jssdkData,'this.jssdkData');
			// wx6bd80db273bdbad9
			const appid = 'wx6bd80db273bdbad9';
			const redirectUri = encodeURIComponent(
				`${window.location.origin}/login?type=wx`
			);
			const wxAuthUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${redirectUri}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`;

			// 跳转微信授权页面
			window.location.href = wxAuthUrl;
		},
	},
	onShow() {
		// 检查是否是从微信授权回调回来的
		const code = this.getQueryString("code");
		const type = this.getQueryString("type");
		if (code && type === "wx" && !!uni.getStorageSync('token')) {
			this.exchangeWxCode(code);
		}
	},

	// 用code换取token
	async exchangeWxCode(code) {
		try {
			uni.showLoading({
				title: "登录中...",
				mask: true,
			});

			const res = await user.userThirdLogin({
				code: code,
				source: "wechat",
			});

			if (res.response.statusCode === 200) {
				// const token = res.data?.token || res.token;
				const userInfo = res.data?.userinfo || res.data.userinfo;

				// if (token) {
				// 	this.login(token);
				// }

				// if (userInfo) {
				// 	this.setUserInfo(userInfo);
				// }
				uni.showToast({
					title: "登录成功",
					icon: "success",
				});
				uni.setStorage({ key: 'token', data: res.data.data.userinfo.token });
				uni.setStorage({ key: 'userInfo', data: res.data.data.userinfo });
				this.redirectToHome();
			} else {
				uni.showToast({
					title: res.msg || res.message || "微信登录失败",
					icon: "none",
				});
			}
		} catch (error) {
			console.error("微信登录失败", error);
			uni.showToast({
				title: "微信登录失败",
				icon: "none",
			});
		} finally {
			this.wxAuthLoading = false;
			uni.hideLoading();
		}
	},

	// 解析URL中的参数
	getQueryString(name) {
		const reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
		const r = window.location.search.substr(1).match(reg);
		if (r != null) {
			return unescape(r[2]);
		}
		return null;
	},
};
</script>

<style lang="scss" scoped>
.login-container {
	padding: 0 60rpx;
	box-sizing: border-box;
	height: 100vh;
	display: flex;
	flex-direction: column;
	background-color: #fff;

	.logo-area {
		flex: 1;
		display: flex;
		align-items: center;
		justify-content: center;

		.logo {
			width: 200rpx;
			height: 200rpx;
			border-radius: 20rpx;
		}
	}

	.form-area {
		flex: 1;
		display: flex;
		flex-direction: column;
		justify-content: flex-end;
		padding-bottom: 100rpx;

		.title {
			font-size: 48rpx;
			font-weight: bold;
			color: #333;
			margin-bottom: 80rpx;
			text-align: center;
		}

		.input-group {
			margin-bottom: 40rpx;

			.input-item {
				height: 100rpx;
				display: flex;
				align-items: center;
				border-bottom: 1rpx solid #e5e5e5;
				margin-bottom: 30rpx;

				.input-icon {
					width: 40rpx;
					height: 40rpx;
					margin-right: 20rpx;
				}

				.input {
					flex: 1;
					font-size: 32rpx;
					height: 80rpx;
					line-height: 80rpx;
				}

				.input-placeholder {
					color: #ccc;
					font-size: 32rpx;
				}
			}
		}

		.flex-between {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 60rpx;
			font-size: 28rpx;
			color: #666;

			.remember-me {
				display: flex;
				align-items: center;

				checkbox {
					transform: scale(0.8);
				}
			}

			.forgot-password {
				color: #7dc5eb;
			}
		}

		.login-btn {
			width: 100%;
			height: 90rpx;
			line-height: 90rpx;
			border-radius: 45rpx;
			background-color: #7dc5eb;
			color: #fff;
			font-size: 32rpx;
			margin-bottom: 40rpx;

			&:after {
				border: none;
			}
		}

		.wx-login-btn {
			width: 100%;
			height: 90rpx;
			line-height: 90rpx;
			border-radius: 45rpx;
			background-color: #7dc5eb;
			color: #fff;
			font-size: 32rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			margin-bottom: 20rpx;
			text-align: center;

			.wx-icon {
				width: 40rpx;
				height: 40rpx;
				margin-right: 10rpx;
			}

			&:after {
				border: none;
			}
		}

		.other-login-btn {
			width: 100%;
			height: 90rpx;
			line-height: 90rpx;
			border-radius: 45rpx;
			background-color: #12b7f5;
			color: #fff;
			font-size: 32rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			margin-bottom: 20rpx;

			.other-icon {
				width: 40rpx;
				height: 40rpx;
				margin-right: 10rpx;
			}

			&:after {
				border: none;
			}
		}

		.switch-login-type {
			text-align: center;
			margin-bottom: 30rpx;
			color: #7dc5eb;
			font-size: 28rpx;
		}

		.agreement {
			margin-top: 40rpx;
			font-size: 24rpx;
			color: #999;
			text-align: center;

			.link {
				color: #7dc5eb;
			}
		}
	}
}
</style>
